<template>
  <div>
    <a-row :gutter="16">
      <!-- 左侧列：树形结构和新增、删除按钮 -->
      <a-col :span="4">
        <a-card>
          <a-tree
            :tree-data="treeData"
            :defaultExpandAll="true"
            show-line
            @select="onSelect"
            @dblclick="DbClick"
          />

          <a-button class="button" type="primary" @click="openAddModal"
            >新增环节</a-button
          >
          <a-button type="primary" @click="deletehuan" danger>删除环节</a-button>
        </a-card>
      </a-col>

      <!-- 右侧列：表格展示 -->
      <a-col :span="20">
        <a-card>
          <a-table
            :columns="columns"
            :dataSource="addtre"
            :expandable="expandable"
            rowKey="processStepsId"
          >
            <template #expandedRowRender="{ record }">
              <a-table
                :columns="columns"
                :dataSource="record.children"
                :pagination="false"
                :rowKey="processStepsId"
                :expandable="expandable"
                :showHeader="false"
              />
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
    <!-- 弹窗组件：新增树节点和表格 -->
    <EntryAddTreeModal
      ref="entryAddTreeModal"
      :direction="addDirection"
      :parentNodeId="selectedNodeId"
      @refresh="queryTree"
    />
    <EntryEnterTableModal
      ref="entryEnterTableModal"
      @refresh="queryTable"
      :ProcessStepID="
        selectedKeys.value && selectedKeys.value.length > 0 ? selectedKeys.value[0] : ''
      "
      :treeData="treeData"
    />
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { craft } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/craft";
import EntryAddTreeModal from "/@/components/entry/add-modal.vue";
import EntryEnterTableModal from "/@/components/entry/enter-modal.vue";
import { smartSentry } from "/@/lib/smart-sentry";

// 初始化树形结构和表格的状态变量
const expandedKeys = ref(["2"]); // 默认展开的节点
const selectedKeys = ref([]); // 当前选中的节点
const tableLoading = ref(false); // 表格加载状态
const total = ref(0);

const selectedNodeId = ref(null); // 记录当前选中的节点 ID
const addDirection = ref(""); // 记录新增方向（上级或下级）
const tableData = ref([]); // 表格数据
// 查询表单状态
const queryFormState = reactive({
  pageNum: 1,
  pageSize: 10,
});
const queryForm = reactive({ ...queryFormState });
// 分页设置
const pagination = computed(() => ({
  total: total.value,
  pageSize: queryFormState.pageSize,
  current: queryFormState.pageNum,
  showTotal: (total) => `总共${total}项`,
}));
const expandable = { defaultExpandAllRows: true };
// 树形数据
const treeData = ref([]);

// 表格列配置
const columns = ref([
  { title: "id", dataIndex: "processStepsId" },
  { title: "环节名称", dataIndex: "stepName", width: 120 },
  { title: "父级", dataIndex: "parentStepId" },
  { title: "能源类型", dataIndex: "energyTypesId", width: 120 },
  { title: "原材料类型", dataIndex: "rawMaterialTypesId" },
  { title: "原辅料类型", dataIndex: "auxiliaryMaterialTypesId" },
  { title: "包装物料类型", dataIndex: "packagingTypesId" },
  { title: "备注", dataIndex: "remarks" },
  { title: "活动类别", dataIndex: "activityCategoriesId" },
  { title: "活动类型", dataIndex: "activityTypesId" },
  { title: "排放源名称", dataIndex: "sourceName" },
]);

// 新增环节的函数，触发弹窗展示
function add() {
  console.log(selectedKeys.value);
  entryAddTreeModal.value.showModal();
}
const parentname = ref("");
const parentid = ref("");
// 选择树节点时的事件
function onSelect(selectedKeysArray, { node }) {
  parentname.value = node.title;
  selectedKeys.value = selectedKeysArray; // 更新 selectedKeys
  selectedNodeId.value = node.key; // 设置选中的节点 ID
}

// 通过双击展示详情弹窗
function DbClick() {
  console.log("DbClick", selectedKeys.value);
  entryEnterTableModal.value.showModal();
}

// 查询树结构数据的函数
const entryAddTreeModal = ref();
// 转换函数：将查询结果转换为 a-tree 的 treeData 格式
function transformData(data) {
  return data.map((node) => ({
    title: node.stepName,
    key: node.processStepsId.toString(),
    children: node.children ? transformData(node.children) : null, // 递归处理多层 children
  }));
}
// 查询表格数据的函数
const entryEnterTableModal = ref();
const addtre = ref(null);
async function queryTable() {
  tableLoading.value = true;
  try {
    // 更新查询表单的页码和每页大小
    queryForm.pageNum = queryFormState.pageNum;
    queryForm.pageSize = queryFormState.pageSize;
    // 执行查询，获取数据
    let queryResult = await craft.query(queryForm);
    // 转换为 a-tree 格式并赋值给 treeData
    treeData.value = transformData(queryResult.data); // 使用转换后的完整树结
    addtre.value = queryResult.data;
    console.log(queryResult.data);
    tableData.value = queryResult.data; // 更新表格数据
    total.value = queryResult.data.total; // 更新总条数s
  } catch (error) {
    smartSentry.captureError(error); // 捕获并记录错误
  } finally {
    tableLoading.value = false; // 关闭加载状态
  }
}
function findParentId(tree, stepName) {
  for (const node of tree) {
    if (node.stepName === stepName) {
      return node.processStepsId;
    } else if (node.children) {
      const result = findParentId(node.children, stepName);
      if (result) {
        return result;
      }
    }
  }
  return null;
}
function openAddModal(direction) {
  if (!selectedKeys.value.length) {
    alert("请选择一个节点进行操作");
    return;
  }
  selectedNodeId.value = selectedKeys.value[0]; // 选中的节点 ID
  addDirection.value = direction; // 设置新增方向
  const parentId = findParentId(addtre.value, parentname.value); // 获取父节点 ID
  console.log(parentId);
  entryAddTreeModal.value.showModal(selectedNodeId.value, parentname.value);
}

function submitNewNode() {
  // 获取新增节点的类型、上级节点 ID 和节点数据
  const direction = props.direction;
  const parentNodeId = props.parentNodeId;
  const newNodeData = {
    // 填写节点的数据
    stepName: newNodeStepName.value,
    energyTypesId: selectedEnergyType.value,
    rawMaterialTypesId: selectedRawMaterialType.value,
    auxiliaryMaterialTypesId: selectedAuxiliaryMaterialType.vaule,
    packagingTypesId: selectedPackagingType.value,
  };

  // 发送新增请求
  craft.addNode({ ...newNodeData, direction, parentNodeId }).then((response) => {
    emit("refresh"); // 成功后刷新树形结构
    closeModal(); // 关闭弹窗
  });
}

// 更新树结构的函数
async function queryTree() {
  try {
    const queryResult = await craft.getTreeData();
    treeData.value = transformData(queryResult.data);
  } catch (error) {
    console.error("树形数据更新失败:", error);
  }
}

// 处理分页或筛选变动
const handlechange = (pagination, filters, sorter) => {
  queryFormState.pageNum = pagination.current; // 更新当前页码
  queryFormState.pageSize = pagination.pageSize; // 更新每页条数
  queryTable(); // 重新查询数据
};
const deletehuan = async () => {
  try {
    if (selectedNodeId.value) {
      await craft.delete(selectedNodeId.value).then(() => {
        queryTree();
      });
    }
  } catch (error) {
    console.log(error);
  }
};
// 组件挂载时，初始化数据查询
onMounted(() => {
  queryTable();
});
</script>

<style lang="less" scoped>
.ant-card {
  min-height: 1200px;
}
.button {
  margin-right: 10px;
}
</style>
